<template>
  <div class="process-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="工艺路线编号">
          <el-input v-model="searchForm.processCode" placeholder="请输入工艺路线编号" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="工艺路线名称">
          <el-input v-model="searchForm.processName" placeholder="请输入工艺路线名称" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="searchForm.isEnabled" placeholder="请选择是否启用" clearable style="width: 180px;">
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" style="margin-left: 10px;">搜索</el-button>
          <el-button @click="resetSearch" style="margin-left: 10px;">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 按钮区域 -->
    <div class="button-container">
      <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="success" icon="Edit" @click="handleEdit">修改</el-button>
      <el-button type="danger" icon="Delete" @click="handleDelete">删除</el-button>
      <el-button type="warning" icon="Download" @click="handleExport">导出Excel</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="processCode" label="工艺路线编号" width="150"></el-table-column>
      <el-table-column prop="processName" label="工艺路线名称" width="150"></el-table-column>
      <el-table-column prop="processDescription" label="工艺路线说明"></el-table-column>
      <el-table-column prop="status" label="是否启用">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'danger'">
            {{ scope.row.status ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="processDesc" label="备注"></el-table-column>
     
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" size="small" icon="Edit" @click="editRow(scope.row)">修改</el-button>
          <el-button type="danger" size="small" icon="Delete" @click="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增工艺路线' : '修改工艺路线'"
      width="1000px"
      class="process-dialog"
      :close-on-click-modal="false"
      :show-close="true"
      @close="closeDialog"
    >
      <!-- 基本信息部分 -->
      <div class="form-section">
        <div class="form-row">
          <div class="form-item">
            <label class="required-label">编号</label>
            <el-input v-model="form.processCode" placeholder="请输入工艺路线编号"></el-input>
          </div>
          <div class="form-switch">
            <el-switch v-model="autoGenerate" inactive-text="" :disabled="dialogType === 'edit'"></el-switch>
            <span>自动生成</span>
          </div>
          
          <div class="form-item name-item">
            <label class="required-label">名称</label>
            <el-input v-model="form.processName" placeholder="请输入工艺路线名称"></el-input>
          </div>
          <div class="form-item status-item">
            <label class="required-label">是否启用</label>
            <div class="radio-group">
              <el-radio v-model="form.status" :label="1">是</el-radio>
              <el-radio v-model="form.status" :label="0">否</el-radio>
            </div>
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-item full-width">
            <label>说明</label>
            <el-input v-model="form.processDescription" type="textarea" :rows="3" placeholder="请输入工艺路线详细说明"></el-input>
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-item full-width">
            <label>备注</label>
            <el-input v-model="form.processDesc" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
          </div>
        </div>
      </div>
      
      <!-- 组成工序标签页 -->
      <div class="tabs-container" v-if="dialogType === 'edit'">
        <div class="tabs-section">
          <div class="tabs-wrapper">
            <div class="tab-header">
              <div class="tab active">组成工序</div>
              <div class="tab-spacer"></div>
            </div>
            
            <div class="tab-content">
              <div class="process-buttons">
                <el-button type="primary" plain size="small" @click="handleAddProcess">
                  <el-icon><Plus /></el-icon>
                  <span>新增</span>
                </el-button>
                <el-button type="primary" plain size="small" @click="handleEditProcess">
                  <el-icon><Edit /></el-icon>
                  <span>修改</span>
                </el-button>
                <el-button type="danger" plain size="small" @click="handleDeleteProcess">
                  <el-icon><Delete /></el-icon>
                  <span>删除</span>
                </el-button>
              </div>
              
              <el-table
                v-loading="processLoading"
                :data="processList"
                @selection-change="handleProcessSelectionChange"
                border
                style="width: 100%"
              >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="序号" type="index" width="60"></el-table-column>
                <el-table-column prop="processCode" label="工序编码" width="120"></el-table-column>
                <el-table-column prop="processName" label="工序名称" width="120"></el-table-column>
                <el-table-column prop="nextProcess" label="下一道工序" width="120"></el-table-column>
                <el-table-column prop="relationshipWithNextProcess" label="与下一道工序关系" width="150"></el-table-column>
                <el-table-column prop="isCritical" label="关键工序" width="100">
                  <template #default="scope">
                    <el-tag v-if="scope.row.isCritical" type="success">是</el-tag>
                    <span v-else>否</span>
                  </template>
                </el-table-column>
                <el-table-column prop="qualityCheck" label="质检确认" width="100">
                  <template #default="scope">
                    <el-tag v-if="scope.row.qualityCheck" type="success">是</el-tag>
                    <span v-else>否</span>
                  </template>
                </el-table-column>
                <el-table-column prop="preparationTime" label="准备时间" width="100"></el-table-column>
                <el-table-column prop="waitingTime" label="等待时间" width="100"></el-table-column>
                <el-table-column prop="ganttColor" label="甘特图显示颜色" width="120">
                  <template #default="scope">
                    <div class="color-box" :style="{backgroundColor: scope.row.ganttColor || '#FFFFFF', border: '1px solid #dcdfe6'}"></div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="scope">
                    <el-button type="primary" plain size="small" @click="editProcessRow(scope.row)">
                      <el-icon><Edit /></el-icon>
                      修改
                    </el-button>
                    <el-button type="danger" plain size="small" @click="deleteProcessRow(scope.row)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="pagination">
                <div class="pagination-info">
                  共 {{ processTotal }} 条
                </div>
                <el-select v-model="processPageSize" class="pagination-size">
                  <el-option :value="10" label="10条/页"></el-option>
                  <el-option :value="20" label="20条/页"></el-option>
                  <el-option :value="50" label="50条/页"></el-option>
                </el-select>
                <el-pagination
                  v-model:current-page="processCurrentPage"
                  :page-size="processPageSize"
                  background
                  layout="prev, pager, next"
                  :total="processTotal"
                  @current-change="handleProcessCurrentChange"
                ></el-pagination>
                <div class="pagination-jump">
                  前往
                  <el-input v-model="jumpPage" class="jump-input" @keyup.enter="handleJumpPage" />
                  页
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工序新增/编辑弹窗 -->
    <el-dialog
      v-model="processDialogVisible"
      :title="processDialogType === 'add' ? '新增工序' : '修改工序'"
      width="500px"
      class="process-form-dialog"
      @close="closeProcessDialog"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="120px"
      >
        <el-form-item label="工序编码" prop="processCode">
          <el-input v-model="processForm.processCode" placeholder="请输入工序编码"></el-input>
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="processForm.processName" placeholder="请输入工序名称"></el-input>
        </el-form-item>
        <el-form-item label="下一道工序" prop="nextProcess">
          <el-input v-model="processForm.nextProcess" placeholder="请输入下一道工序"></el-input>
        </el-form-item>
        <el-form-item label="与下一工序关系" prop="relationship">
          <el-select v-model="processForm.relationship" placeholder="请选择与下一工序关系" clearable>
            <el-option value="F-to-F" label="F-to-F"></el-option>
            <el-option value="S-to-F" label="S-to-F"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键工序" prop="isCritical" class="is-switch">
          <el-switch 
            v-model="processForm.isCritical" 
            :active-value="true"
            :inactive-value="false"
            active-text="是" 
            inactive-text="否">
          </el-switch>
        </el-form-item>
        <el-form-item label="质检确认" prop="qualityCheck" class="is-switch">
          <el-switch 
            v-model="processForm.qualityCheck" 
            :active-value="true"
            :inactive-value="false"
            active-text="是" 
            inactive-text="否">
          </el-switch>
        </el-form-item>
        <el-form-item label="准备时间" prop="prepTime">
          <el-date-picker
            v-model="processForm.preparationTime"
            type="datetime"
            placeholder="请选择准备时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="等待时间" prop="waitingTime">
          <el-date-picker
            v-model="processForm.waitingTime"
            type="datetime"
            placeholder="请选择等待时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="甘特图显示颜色" prop="ganttColor">
          <el-color-picker v-model="processForm.ganttColor" show-alpha></el-color-picker>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="processSubmitting" @click="submitProcessForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import http from '@/api/http.js'
import axios from 'axios'
import store from '@/store/index'

// 定义接口
interface ProcessItem {
  id: string | number;
  processCode: string;
  processName: string;
  processDescription: string;
  status: number;
  processDesc: string;
}

// 搜索表单
const searchForm = reactive({
  processCode: '',
  processName: '',
  isEnabled: ''
})

// 重置搜索
const resetSearch = () => {
  searchForm.processCode = ''
  searchForm.processName = ''
  searchForm.isEnabled = ''
  search()
}

// 表格数据
const tableData = ref<ProcessItem[]>([])
const loading = ref(false)
const selectedRows = ref<ProcessItem[]>([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const activeTab = ref('basicInfo') // Tab页选择
const activeProcessTab = ref('compositionProcess') // 工序Tab页选择
const autoGenerate = ref(false) // 自动生成编号
const formRef = ref<FormInstance>()
const form = reactive({
  id: '',
  processCode: '',
  processName: '',
  processDescription: '',
  status: 1,
  processDesc: ''
})

// 监听自动生成开关状态
watch(autoGenerate, (newVal) => {
  if (newVal && dialogType.value === 'add') {
    // 开启自动生成时，生成编号
    generateProcessCode()
  } else if (!newVal) {
    // 关闭自动生成时，清空编号
    form.processCode = ''
  }
})

// 工序相关数据
const processList = ref<any[]>([]) // 工序列表数据
const processLoading = ref(false) // 工序加载状态
const processCurrentPage = ref(1) // 工序当前页
const processPageSize = ref(10) // 工序每页大小
const processTotal = ref(0) // 工序总数
const selectedProcessRows = ref<any[]>([]) // 选中的工序行

// 表单验证规则
const rules = reactive<FormRules>({
  processCode: [
    { required: true, message: '请输入工艺路线编号', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9-_]+$/, message: '编号只能包含字母、数字、连字符和下划线', trigger: 'blur' }
  ],
  processName: [
    { required: true, message: '请输入工艺路线名称', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  processDescription: [
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ],
  processDesc: [
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ]
})

// 分页跳转
const jumpPage = ref(1)
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value.toString())
  if (isNaN(pageNum) || pageNum < 1 || pageNum > Math.ceil(processTotal.value / processPageSize.value)) {
    ElMessage.warning('请输入有效的页码')
    return
  }
  processCurrentPage.value = pageNum
  fetchCompositionProcessData()
}

// 初始加载数据
onMounted(() => {
  fetchData()
})

// 获取表格数据
const fetchData = async () => {
  loading.value = true
  try {
    // 构建URL参数
    let queryParams = []
    if (searchForm.processCode) {
      queryParams.push(`ProcessCode=${encodeURIComponent(searchForm.processCode)}`)
    }
    if (searchForm.processName) {
      queryParams.push(`ProcessName=${encodeURIComponent(searchForm.processName)}`)
    }
    if (searchForm.isEnabled !== undefined && searchForm.isEnabled !== '') {
      queryParams.push(`Status=${searchForm.isEnabled}`)
    }
    queryParams.push(`Page=${currentPage.value}`)
    queryParams.push(`PageSize=${pageSize.value}`)
    
    const queryString = queryParams.length > 0 ? '?' + queryParams.join('&') : ''
    
    // 使用http封装的GET请求方法
    const result = await http.get(`/api/ProductionManagement/getProcessPageData${queryString}`, {}, true)
    console.log('API响应数据:', result)
    
    if (result && result.status) {
      tableData.value = result.data?.rows || []
      total.value = result.data?.total || 0
    } else {
      ElMessage.error(result?.message || '获取数据失败')
    }
  } catch (error: any) {
    console.error('获取数据失败:', error)
    ElMessage.error(`获取数据失败: ${error.message || error}`)
  } finally {
    loading.value = false
  }
}

// 搜索
const search = () => {
  currentPage.value = 1
  fetchData()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 处理表格选择变化
const handleSelectionChange = (rows: ProcessItem[]) => {
  selectedRows.value = rows
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm() // 确保表单被完全重置
  autoGenerate.value = false // 默认不启用自动生成
  dialogVisible.value = true
}

// 编辑
const handleEdit = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条记录进行修改')
    return
  }
  
  dialogType.value = 'edit'
  const row = selectedRows.value[0]
  Object.assign(form, row)
  // 编辑模式下关闭自动生成
  autoGenerate.value = false
  dialogVisible.value = true
  // 打开编辑对话框后，立即加载组成工序数据
  setTimeout(() => {
    console.log('编辑加载组成工序，工艺路线ID:', row.id, '工艺路线编号:', row.processCode)
    fetchCompositionProcessData(row.id)
  }, 200)
}

// 编辑行
const editRow = (row: any) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  // 编辑模式下关闭自动生成
  autoGenerate.value = false
  dialogVisible.value = true
  // 打开编辑对话框后，立即加载组成工序数据
  setTimeout(() => {
    console.log('编辑加载组成工序，工艺路线ID:', row.id, '工艺路线编号:', row.processCode)
    fetchCompositionProcessData(row.id)
  }, 200)
}

// 删除
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm('确定要删除选中的记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 获取所选记录的ID数组
      const ids = selectedRows.value.map(row => row.id)
      console.log('批量删除ID列表:', ids)
      
      // 使用http封装的post方法
      const url = 'api/ProductionManagement/batchDeleteProcess'
      console.log('批量删除URL:', url)
      
      // 调用API删除数据
      const result = await http.post(url, ids, true)
      
      console.log('批量删除响应:', result)
      
      if (result && result.status) {
        ElMessage.success('批量删除成功')
        fetchData()
      } else {
        ElMessage.error(result?.message || '批量删除失败')
      }
    } catch (error: any) {
      console.error('批量删除失败:', error)
      ElMessage.error(`批量删除失败: ${error.message || error}`)
    }
  }).catch(() => {})
}

// 删除行
const deleteRow = (row: ProcessItem) => {
  ElMessageBox.confirm('确定要删除该记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log('单个删除ID:', row.id)
      
      // 创建仅包含一个ID的数组，与批量删除使用相同格式
      const ids = [row.id]
      
      // 使用http封装的post方法
      const url = 'api/ProductionManagement/batchDeleteProcess'
      console.log('单个删除URL:', url)
      
      // 调用API删除数据
      const result = await http.post(url, ids, true)
      
      console.log('单个删除响应:', result)
      
      if (result && result.status) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(result?.message || '删除失败')
      }
    } catch (error: any) {
      console.error('删除失败:', error)
      ElMessage.error(`删除失败: ${error.message || error}`)
    }
  }).catch(() => {})
}



// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = ''
  form.processCode = ''
  form.processName = ''
  form.processDescription = ''
  form.status = 1
  form.processDesc = ''
  autoGenerate.value = false // 重置自动生成开关
}

// 提交中状态
const submitting = ref(false)

// 处理提交按钮点击
const handleSubmit = () => {
  console.log('点击了确定按钮 - 触发提交')
  submitDirectly()
}

// 直接提交表单数据
const submitDirectly = async () => {
  console.log('开始直接提交表单')
  
  // 基本验证
  if (!form.processCode) {
    ElMessage.warning('请输入工艺路线编号')
    return
  }
  
  if (!form.processName) {
    ElMessage.warning('请输入工艺路线名称')
    return
  }
  
      try {
        submitting.value = true
        
    // 准备数据
    const formData = {
      Id: parseInt(form.id) || 0,
      ProcessCode: form.processCode,
      ProcessName: form.processName,
      ProcessDescription: form.processDescription || '',
      Status: form.status ? 1 : 0,
      ProcessDesc: form.processDesc || ''
    }
    
    console.log('准备提交的数据:', formData)
    
    // 确定API端点
    const isAdd = dialogType.value === 'add'
    const endpoint = isAdd ? 'addProcess' : 'updateProcess'
    
    // 使用http封装方法
    const apiUrl = `api/ProductionManagement/${endpoint}`
    console.log('请求URL:', apiUrl)
    
    // 调用http封装的post方法发送请求
    const result = await http.post(apiUrl, formData, true)
    console.log('响应内容:', result)
    
    if (result && result.status) {
      ElMessage.success(isAdd ? '新增成功' : '修改成功')
      dialogVisible.value = false
      resetForm()
      fetchData()
    } else {
      ElMessage.error(result?.message || (isAdd ? '新增失败' : '修改失败'))
    }
  } catch (error: any) {
    console.error('提交过程中发生错误:', error)
    ElMessage.error('提交失败: ' + (error.message || '未知错误'))
  } finally {
            submitting.value = false
  }
}

// 生成随机工艺路线编号
const generateProcessCode = () => {
  const prefix = 'PROC-'
  const timestamp = new Date().getTime().toString().substring(6) // 使用时间戳后几位
  const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0') // 生成6位随机数
  form.processCode = `${prefix}${random}-${Math.floor(Math.random() * 10)}`
  ElMessage.success('生成编号成功')
}

// 新增/编辑弹窗
const processDialogVisible = ref(false)
const processDialogType = ref('add') // 'add' 或 'edit'
const processFormRef = ref<FormInstance>()
const processForm = reactive({
  id: '',
  processCode: '',
  processName: '',
  nextProcess: '',
  relationship: '',
  isCritical: false,
  qualityCheck: false,
  preparationTime: '',
  waitingTime: '',
  ganttColor: '#87CEFA' // 默认浅蓝色
})

// 表单验证规则
const processRules = reactive<FormRules>({
  processCode: [
    { required: true, message: '请输入工序编码', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9-_]+$/, message: '编号只能包含字母、数字、连字符和下划线', trigger: 'blur' }
  ],
  processName: [
    { required: true, message: '请输入工序名称', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  nextProcess: [
    { required: true, message: '请输入下一道工序', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  relationship: [
    { required: true, message: '请选择与下一工序关系', trigger: 'change' }
  ],
  preparationTime: [
    { required: false, message: '请选择准备时间', trigger: 'change' }
  ],
  waitingTime: [
    { required: false, message: '请选择等待时间', trigger: 'change' }
  ]
})

// 提交工序表单
const processSubmitting = ref(false)
const submitProcessForm = async () => {
  if (!processFormRef.value) return
  
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        processSubmitting.value = true
        
        // 根据Swagger UI显示的路径
        const url = processDialogType.value === 'add' 
          ? 'api/ProductionManagement/addCompositionProcess'
          : 'api/ProductionManagement/updateCompositionProcess'
          
        // 确保字段名与后台一致 - 根据数据库结构映射字段
        const formData = {
          Id: parseInt(processForm.id) || 0,
          ProcessId: parseInt(form.id) || 0, // 主工艺路线ID
          Code: form.processCode, // 父工艺路线编号
          ProcessCode: processForm.processCode, // 工序编码
          ProcessName: processForm.processName, // 工序名称
          NextProcess: processForm.nextProcess, // 下一道工序
          RelationshipWithNextProcess: processForm.relationship, // 与下一道工序关系
          CriticalProcess: processForm.isCritical ? '是' : '否', // 关键工序 - 使用字符串类型
          QualityInspectionConfirmation: processForm.qualityCheck ? '是' : '否', // 质检确认 - 使用字符串类型
          PreparationTime: processForm.preparationTime || null, // 准备时间
          WaitingTime: processForm.waitingTime || null, // 等待时间
          Color: processForm.ganttColor?.replace('#', '') || null // 甘特图颜色 (去掉#前缀)
        }
        
        console.log('工序表单JSON:', JSON.stringify(formData))
        
        // 设置正确的 Content-Type
        const headers = {
          'Content-Type': 'application/json-patch+json'
        }
        
        // 使用http封装的post方法，确保设置了正确的headers
        const response = await http.post(url, formData, true, headers)
        
        console.log('工序响应数据:', response)
        
        if (response && response.status) {
          ElMessage.success(processDialogType.value === 'add' ? '新增工序成功' : '修改工序成功')
          processDialogVisible.value = false
          fetchCompositionProcessData() // 刷新工序列表
        } else {
          const errorMsg = response?.message || (processDialogType.value === 'add' ? '新增工序失败' : '修改工序失败')
          ElMessage.error(errorMsg)
          console.error('工序API返回错误:', errorMsg)
        }
      } catch (error: any) {
        console.error('提交工序表单失败:', error)
        ElMessage.error(`提交失败: ${error.message || '未知错误'}`)
      } finally {
        processSubmitting.value = false
      }
    } else {
      ElMessage.warning('请完善工序表单信息')
    }
  })
}

// 新增工序
const handleAddProcess = () => {
  // 确保已有父工艺路线ID
  if (!form.id) {
    ElMessage.warning('请先保存工艺路线基本信息')
    return
  }
  
  processDialogType.value = 'add'
  resetProcessForm()
  
  // 设置默认值
  processForm.id = ''  // 空字符串而不是数字0
  // 生成工序编号 (可选)
  processForm.processCode = generateProcessSequenceCode()
  
  processDialogVisible.value = true
}

// 生成工序编号
const generateProcessSequenceCode = () => {
  // 生成6位随机数字
  const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
  return random
}

// 编辑工序
const handleEditProcess = () => {
  if (selectedProcessRows.value.length !== 1) {
    ElMessage.warning('请选择一条工序记录进行修改')
    return
  }
  
  processDialogType.value = 'edit'
  const row = selectedProcessRows.value[0]
  
  // 创建一个干净的数据副本
  const processData = { ...row }
  
  // 映射字段
  // 处理颜色值，确保显示正确
  if (row.color) {
    processData.ganttColor = row.color.startsWith('#') ? row.color : '#' + row.color
  }
  
  // 映射字段名 - 将字符串转换为布尔值
  if (row.qualityInspectionConfirmation !== undefined) {
    processData.qualityCheck = row.qualityInspectionConfirmation === '是'
  }
  
  // 根据数据库字段类型修正
  if (row.criticalProcess !== undefined) {
    processData.isCritical = row.criticalProcess === '是'
  }
  
  if (row.relationshipWithNextProcess) {
    processData.relationship = row.relationshipWithNextProcess
  }
  
  console.log('准备编辑工序，数据:', processData)
  Object.assign(processForm, processData)
  processDialogVisible.value = true
}

// 编辑工序行
const editProcessRow = (row: any) => {
  processDialogType.value = 'edit'
  
  // 创建一个干净的数据副本
  const processData = { ...row }
  
  // 映射字段
  // 处理颜色值，确保显示正确
  if (row.color) {
    processData.ganttColor = row.color.startsWith('#') ? row.color : '#' + row.color
  }
  
  // 映射字段名 - 将字符串转换为布尔值
  if (row.qualityInspectionConfirmation !== undefined) {
    processData.qualityCheck = row.qualityInspectionConfirmation === '是'
  }
  
  // 根据数据库字段类型修正
  if (row.criticalProcess !== undefined) {
    processData.isCritical = row.criticalProcess === '是'
  }
  
  if (row.relationshipWithNextProcess) {
    processData.relationship = row.relationshipWithNextProcess
  }
  
  // 添加调试日志
  console.log('准备编辑工序，原始数据:', row)
  console.log('准备编辑工序，映射后数据:', processData)
  
  Object.assign(processForm, processData)
  processDialogVisible.value = true
}

// 删除工序
const handleDeleteProcess = () => {
  if (selectedProcessRows.value.length === 0) {
    ElMessage.warning('请至少选择一条工序记录')
    return
  }

  ElMessageBox.confirm('确定要删除选中的工序记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 获取所选记录的ID数组
      const ids = selectedProcessRows.value.map(row => row.id)
      console.log('批量删除工序ID列表:', ids)
      
      // 使用http封装的post方法
      const url = 'api/ProductionManagement/batchDeleteCompositionProcess'
      console.log('批量删除工序URL:', url)
      
      // 设置正确的 Content-Type
      const headers = {
        'Content-Type': 'application/json-patch+json'
      }
      
      // 调用API删除数据
      const result = await http.post(url, ids, true, headers)
      
      console.log('批量删除工序响应:', result)
      
      if (result && result.status) {
        ElMessage.success('批量删除工序成功')
        fetchCompositionProcessData()
        } else {
        ElMessage.error(result?.message || '批量删除工序失败')
        }
      } catch (error: any) {
      console.error('批量删除工序失败:', error)
      ElMessage.error(`批量删除工序失败: ${error.message || error}`)
    }
  }).catch(() => {
    // 用户取消删除，不做任何操作
  })
}

// 删除工序行
const deleteProcessRow = (row: any) => {
  ElMessageBox.confirm('确定要删除该工序记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log('单个删除工序ID:', row.id)
      
      // 创建仅包含一个ID的数组
      const ids = [row.id]
      
      // 使用http封装的post方法
      const url = 'api/ProductionManagement/batchDeleteCompositionProcess'
      console.log('单个删除工序URL:', url)
      
      // 设置正确的 Content-Type
      const headers = {
        'Content-Type': 'application/json-patch+json'
      }
      
      // 调用API删除数据
      const result = await http.post(url, ids, true, headers)
      
      console.log('单个删除工序响应:', result)
      
      if (result && result.status) {
        ElMessage.success('删除工序成功')
        fetchCompositionProcessData()
    } else {
        ElMessage.error(result?.message || '删除工序失败')
      }
    } catch (error: any) {
      console.error('删除工序失败:', error)
      ElMessage.error(`删除工序失败: ${error.message || error}`)
    }
  }).catch(() => {
    // 用户取消删除，不做任何操作
  })
}

// 处理工序分页大小变化
const handleProcessSizeChange = (val: number) => {
  processPageSize.value = val
  fetchCompositionProcessData()
}

// 处理工序当前页变化
const handleProcessCurrentChange = (val: number) => {
  processCurrentPage.value = val
  fetchCompositionProcessData()
}

// 监听tab切换，加载相应数据
watch(activeTab, (newVal) => {
  if (newVal === 'compositionProcess' && dialogType.value === 'edit') {
    fetchCompositionProcessData()
  }
})

// 获取组成工序数据
const fetchCompositionProcessData = async (processId?: number | string) => {
  // 优先使用传入的processId，没有则使用当前表单的id
  const currentProcessId = processId || form.id
  if (!currentProcessId) {
    console.log('缺少工艺路线ID，无法加载组成工序')
    return
  }
  
  processLoading.value = true
  try {
    // 根据Swagger UI显示的API，使用Code参数
    const code = form.processCode
    if (!code) {
      console.log('缺少工艺路线编号，无法加载组成工序')
      return
    }
    
    // 使用正确的API路径，按照Code查询
    const url = `api/ProductionManagement/getCompositionProcessPageData?Code=${encodeURIComponent(code)}&Page=${processCurrentPage.value}&PageSize=${processPageSize.value}`
    console.log('获取组成工序URL:', url)
    
    const result = await http.get(url, {}, true)
    
    console.log('组成工序响应数据:', result)
    
    if (result && result.status) {
      // 确保颜色值正确显示
      const rows = result.data?.rows || []
      processList.value = rows.map((row: any) => {
        // 处理颜色
        if (row.color && !row.color.startsWith('#')) {
          row.ganttColor = '#' + row.color
        } else {
          row.ganttColor = row.color || row.ganttColor || '#FFFFFF'
        }
        
        // 确保日期字段格式正确
        if (row.preparationTime) {
          row.preparationTime = row.preparationTime
        }
        
        if (row.waitingTime) {
          row.waitingTime = row.waitingTime
        }
        
        // 映射字段名
        if (row.relationshipWithNextProcess) {
          row.relationship = row.relationshipWithNextProcess
        } else if (row.relationship) {
          row.relationshipWithNextProcess = row.relationship
        }
        
        // 将字符串值转换为布尔值 - 根据数据库字段类型修正
        if (row.criticalProcess !== undefined) {
          row.isCritical = row.criticalProcess === '是'
        }
        
        if (row.qualityInspectionConfirmation !== undefined) {
          row.qualityCheck = row.qualityInspectionConfirmation === '是'
        }
        
        // 添加调试日志，查看值转换情况
        console.log(`行数据 ${row.id} - criticalProcess: ${row.criticalProcess}, isCritical: ${row.isCritical}, qualityInspectionConfirmation: ${row.qualityInspectionConfirmation}, qualityCheck: ${row.qualityCheck}`)
        
        return row
      })
      processTotal.value = result.data?.total || 0
    } else {
      ElMessage.error(result?.message || '获取组成工序数据失败')
    }
  } catch (error: any) {
    console.error('获取组成工序数据失败:', error)
    ElMessage.error(`获取组成工序数据失败: ${error.message || error}`)
  } finally {
    processLoading.value = false
  }
}

// 重置工序表单
const resetProcessForm = () => {
  if (processFormRef.value) {
    processFormRef.value.resetFields()
  }
  
  // 手动重置所有字段，确保彻底清空
  processForm.id = ''
  processForm.processCode = ''
  processForm.processName = ''
  processForm.nextProcess = ''
  processForm.relationship = ''
  processForm.isCritical = false
  processForm.qualityCheck = false
  processForm.preparationTime = ''
  processForm.waitingTime = ''
  processForm.ganttColor = '#87CEFA' // 默认浅蓝色
}

// 处理对话框关闭
const handleDialogClose = () => {
  dialogVisible.value = false
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm() // 重置表单数据
}

// 关闭工序对话框
const closeProcessDialog = () => {
  processDialogVisible.value = false
  resetProcessForm()
}

// 处理工序表格选择变化
const handleProcessSelectionChange = (rows: any[]) => {
  selectedProcessRows.value = rows
}

// 导出Excel
const handleExport = async () => {
  try {
    loading.value = true
    ElMessage.info('正在准备导出数据，请稍候...')
    
    // 构建URL参数，使用当前搜索条件
    let queryParams = []
    if (searchForm.processCode) {
      queryParams.push(`ProcessCode=${encodeURIComponent(searchForm.processCode)}`)
    }
    if (searchForm.processName) {
      queryParams.push(`ProcessName=${encodeURIComponent(searchForm.processName)}`)
    }
    if (searchForm.isEnabled !== undefined && searchForm.isEnabled !== '') {
      queryParams.push(`Status=${searchForm.isEnabled}`)
    }
    
    // 导出不分页，获取所有数据
    const queryString = queryParams.length > 0 ? '?' + queryParams.join('&') : ''
    
    // 使用API导出功能
    const url = `/api/ProductionManagement/exportProcessToExcel${queryString}`
    
    // 获取认证信息
    const token = store.getters.token
    
    // 使用axios直接发送请求并处理二进制响应
    const response = await axios({
      method: 'GET',
      url: url,
      responseType: 'blob', // 关键设置：以二进制blob接收响应
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    // 创建Blob链接
    const blob = new Blob([response.data], { 
      type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    
    // 获取文件名
    const fileName = `工艺路线导出_${new Date().toISOString().split('T')[0].replace(/-/g, '_')}.xlsx`
    
    // 创建临时下载链接并触发下载
    const downloadLink = document.createElement('a')
    downloadLink.href = URL.createObjectURL(blob)
    downloadLink.download = fileName
    document.body.appendChild(downloadLink)
    downloadLink.click()
    
    // 清理DOM
    setTimeout(() => {
      document.body.removeChild(downloadLink)
      URL.revokeObjectURL(downloadLink.href)
    }, 100)
    
    ElMessage.success('导出Excel成功')
  } catch (error: any) {
    console.error('导出Excel失败:', error)
    ElMessage.error(`导出Excel失败: ${error.message || error}`)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.process-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container .el-form-item {
  margin-bottom: 10px;
  margin-right: 15px;
}

.search-container .el-select {
  min-width: 180px;
}

.button-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.code-input-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.composition-process-container {
  padding: 20px;
}

.dialog-content {
  display: flex;
  gap: 20px;
}

.basic-info-section {
  flex: 1;
}

.process-section {
  flex: 1;
}

.process-header {
  margin-bottom: 20px;
}

.enable-switch {
  display: flex;
  gap: 10px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.required-label {
  font-size: 14px;
  margin-right: 15px;
  white-space: nowrap;
  color: #606266;
}

.required-label::before {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}

.full-width {
  width: 100%;
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.full-width label {
  margin-right: 15px;
  margin-top: 5px;
  white-space: nowrap;
  color: #606266;
}

.full-width .el-textarea {
  width: 100%;
}

.composition-process-panel {
  margin-top: 20px;
}

.process-tabs {
  margin-bottom: 15px;
}

.process-button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.process-button-group .el-button {
  padding: 8px 15px;
}

.el-table {
  margin-bottom: 20px;
  border-radius: 4px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
  gap: 15px;
  border-top: 1px solid #ebeef5;
}

.pagination-info {
  margin-right: auto;
}

.pagination-size {
  width: 110px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 5px;
}

.jump-input {
  width: 50px;
}

.dialog-footer {
  /* 添加自定义的对话框底部样式 */
}

.color-box {
  width: 30px;
  height: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  display: inline-block;
}

/* 工序新增/编辑弹窗样式 */
.process-form-dialog .el-dialog__body {
  padding: 20px 30px;
}

.process-form-dialog .el-form-item {
  margin-bottom: 20px;
}

.process-dialog {
  .el-dialog__body {
    padding: 25px 30px;
  }
  
  .el-dialog__header {
    padding: 15px 30px;
    margin-right: 0;
  }
  
  .el-dialog__footer {
    padding: 15px 30px;
    border-top: 1px solid #ebeef5;
  }
}

.form-section {
  margin-bottom: 25px;
}

.form-row {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.form-item {
  flex: 1;
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.form-item:last-child {
  margin-right: 0;
}

.form-switch {
  display: flex;
  align-items: center;
  margin-left: 5px;
  margin-right: 20px;
}

.name-item {
  flex: 2;
}

.tabs-section {
  margin-top: 25px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 20px;
}

.tab-header {
  display: flex;
  background-color: #f5f7fa;
  border-bottom: 1px solid #EBEEF5;
  padding: 0 20px;
}

.tab {
  padding: 12px 20px 12px 0;
  cursor: pointer;
  color: #409EFF;
  font-weight: 500;
  border-bottom: 2px solid #409EFF;
}

.tab-spacer {
  flex-grow: 1;
  border-bottom: 1px solid #EBEEF5;
}

.tab-content {
  padding: 20px;
}

.process-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

.process-buttons .el-button {
  padding: 8px 15px;
}

.tabs-wrapper {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
}

.tabs-section {
  margin-top: 25px;
  margin-bottom: 20px;
}

.tabs-container {
  margin-top: 20px;
}

/* 开关样式 */
.el-switch {
  margin-right: 10px;
}

.el-switch :deep(.el-switch__core) {
  width: 50px !important; /* 增加开关宽度 */
}

.el-switch :deep(.el-switch__label) {
  font-size: 14px;
  color: #606266;
}

.el-switch :deep(.el-switch__label.is-active) {
  color: #409EFF;
}

.el-form-item.is-switch {
  display: flex;
  align-items: center;
}
</style>